package cn.edu.dgut.filter;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;


@WebFilter("/*")
public class EntityManagerFilter implements Filter {

    private EntityManagerFactory emf;

    @Override
    public void init(FilterConfig filterConfig) {
        emf = Persistence.createEntityManagerFactory("MyJPADemoPU");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        String uri = ((HttpServletRequest)request).getRequestURI();
        if(uri.contains("/RegisterServlet")||uri.contains("/login/dgut")||uri.contains("/checkInfo")||uri.contains("/uploadImage")
            ||uri.contains("/LocalLoginServlet")||uri.contains("/changeInfo")||uri.contains("/bindInfo")||uri.contains("info.jsp")
        ) {

            EntityManager em = emf.createEntityManager();
            EntityTransaction tx = em.getTransaction();

            tx.begin();
            request.setAttribute("_entity.manager", em);
            try {
                chain.doFilter(request, response);
                tx.commit();
            } catch (IOException | ServletException th) {
                tx.rollback();
                throw th;
            } finally {
                em.close();
            }
        }else {
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {
        emf.close();
    }

}
